package io.lkt.modules.sys.controller;

import io.lkt.common.dto.ArticleInfoTemp;
import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.util.Query;
import io.lkt.common.util.SpringContextUtil;
import io.lkt.common.utils.*;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.HttpGetPostUtils;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.redis.SysConfigRedis;
import io.lkt.modules.sys.sensitive.VideoParse;
import io.lkt.modules.sys.service.*;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import io.lkt.modules.sys.utils.SysConstant;
//import io.lkt.modules.sys.utils.WebSpiderThreadUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/sys/bvideoinfo"})
public class BVideoInfoController extends AbstractController
{
    private static final Logger logger = LoggerFactory.getLogger(BVideoInfoController.class);
    @Autowired
    private BVideoInfoService bVideoInfoService;
    @Autowired
    private BArticleInfoService bArticleInfoService;
    @Autowired
    private BArticleTypeInfoService bArticleTypeInfoService;
    @Autowired
    BBrandInfoService bBrandInfoService;
    @Autowired
    BUserInfoService bUserInfoService;
    @Autowired
    SysConfigRedis redisTemplate;
    @Autowired
    RedisCacheUtil redisCacheUtil;
    @Value("${serviceUrls}")
    private String serviceUrls;
    @Autowired
    BArticleGzhService bArticleGzhService;

    @RequestMapping({"/videoUrl"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R videoUrl(HttpServletRequest request)
    {
        String url = request.getParameter("url");
        String href = "";
        Map<String, Object> map = new HashMap();
        try
        {
            href = urlMap(url);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return R.ok().put("map", href);
    }

    /**
     * 查询头条标题
     * @return
     */
    @RequestMapping("/HeadlineTitle")
    @RequiresPermissions("sys:barticletypeinfo:list")
    public R HeadlineTitle(){
        List<HeadlineTitleInfo> headTitleMap = this.bVideoInfoService.HeadlineTitle();
        return R.ok().put("titles",headTitleMap);
    }

    public String urlMap(String url)
            throws Exception
    {
        Map<String, Object> map = new HashMap();
        Document document = Jsoup.connect(url).get();
        Elements a = document.getElementsByTag("html");
        Elements img = document.select("img");
        List<String> list = new ArrayList();
        for (Element ele : img)
        {
            String src = "<img src=\"" + ele.absUrl("src") + '"' + "/>";
            list.add(src);
        }
        map.put("text", a.html());
        map.put("img", list);
        return a.html();
    }

    @RequestMapping({"/list"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R list(@RequestParam Map<String, Object> params)
            throws Exception
    {
        PageUtils page = this.bVideoInfoService.queryPage(params);
        return R.ok().put("page", page);
    }

    @RequestMapping({"/queryList"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    public R queryList(@RequestParam Map<String, Object> params)
    {
        System.out.println(params);
        Query query = new Query(params);
        List<BArticleInfoEntity> brandList = this.bVideoInfoService.queryList(query);
        System.out.println(brandList.size());
        for (BArticleInfoEntity bArticleInfoEntity : brandList)
        {
            if ((bArticleInfoEntity.getCreateUser() != null) && (!bArticleInfoEntity.getCreateUser().equals(""))) {
                bArticleInfoEntity.setUserName(bArticleInfoEntity.getCreateUser());
            } else if ((bArticleInfoEntity.getArticleSource() != null) && (bArticleInfoEntity.getArticleSource().intValue() == 1)) {
                bArticleInfoEntity.setUserName("管理员");
            }
            if (bArticleInfoEntity.getArticleTypeId() == null)
            {
                BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfoEntity.getArticleBrandId());
                if (bBrandInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bBrandInfoEntity.getBrandName());
                }
            }
            else
            {
                BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfoEntity.getArticleTypeId());
                if (bArticleTypeInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                }
            }
        }
        int total = this.bVideoInfoService.queryTotal(query).intValue();
        PageUtils pageUtil = new PageUtils(brandList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping({"/info/{id}"})
    @RequiresPermissions({"sys:barticleinfo:info"})
    public R info(@PathVariable("id") Integer id)
    {
        BArticleInfoEntity bVideoInfo = (BArticleInfoEntity)this.bVideoInfoService.getById(id);
        int type = 0;
        if (bVideoInfo.getArticleBrandId() != null)
        {
            BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bVideoInfo.getArticleBrandId());
            if (bBrandInfoEntity != null) {
                bVideoInfo.setBrandName(bBrandInfoEntity.getBrandName());
            }
        }
        if (bVideoInfo.getArticleTypeId() != null)
        {
            BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bVideoInfo.getArticleTypeId());
            if (bArticleTypeInfoEntity != null) {
                bVideoInfo.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
            }
            type = 1;
        }
        // 查询头条标题id start yl 20200624
        List<Integer> headlineTitleIds = this.bArticleInfoService.selectHeadlineIdsByArticleId(id);
        if (CollectionUtils.isNotEmpty(headlineTitleIds)){
            bVideoInfo.setHeadlineTitleIds( headlineTitleIds
                    .stream()
                    .map(headlineTitleId -> headlineTitleId +"")
                    .collect(Collectors.joining(",")));
        }
        // 查询头条标题id end yl 20200624
        JSONArray jsonArray = new JSONArray();
        String content = bVideoInfo.getArticleContent();
        if (bVideoInfo.getArticleVersionNum().intValue() == 1) {
            try
            {
                jsonArray = JSONArray.fromObject(bVideoInfo.getArticleContent());
            }
            catch (Exception e)
            {
                System.out.println("文章内容存在问题：" + content);
                String error = "[{\"textContent\": \"文章内容有误\",\"textType\": 1}]";
                jsonArray = JSONArray.fromObject(error);
            }
        }
        return R.ok().put("bVideoInfo", bVideoInfo).put("type", Integer.valueOf(type)).put("jsonArray", jsonArray);
    }

    @RequestMapping({"/save"})
    @RequiresPermissions({"sys:barticleinfo:save"})
    public R save(@RequestBody BArticleInfoEntity bVideoInfo)
    {
        for(String k: SysConstant.KeyWorks){
            if(bVideoInfo.getArticleTitle()!=null && bVideoInfo.getArticleTitle().contains(k)){
                return R.error("标题中不能包含“"+k+"”，请检查后修正.");
            }
            if(bVideoInfo.getArticleDesc()!=null && bVideoInfo.getArticleDesc().contains(k)){
                return R.error("配文中不能包含“"+k+"”，请检查后修正.");
            }
        }

        if ((bVideoInfo.getBrandName().equals("")) && (bVideoInfo.getArticleTypeName().equals(""))) {
            return R.error("请选择品牌或分类");
        }
        bVideoInfo.setCreateTime(new Date());
        bVideoInfo.setModifyTime(new Date());
        bVideoInfo.setArticleSource(Integer.valueOf(1));
        bVideoInfo.setArticleStatus(Integer.valueOf(1));
        bVideoInfo.setSpiderProcessStatus(Integer.valueOf(1));
//        bVideoInfo.setArticleVersionNum(Integer.valueOf(2));
        bVideoInfo.setSType("后台录入");
        bVideoInfo.setResourceType(Integer.valueOf(2));
        bVideoInfo.setArticleBrandId(null);
        bVideoInfo.setArticleTypeId(null);
        SysUserEntity curUser = getUser();
        bVideoInfo.setCreateUser(curUser.getUsername());

        if (!bVideoInfo.getArticleTypeName().equals(""))
        {
            BArticleTypeInfoEntity articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(bVideoInfo.getArticleTypeName());
            if (articleTypeInfoEntity != null)
            {
                bVideoInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                // 删除分类 top50 缓存 start
                String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + articleTypeInfoEntity.getId();
                redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
                // 删除分类 top50 缓存 end
                this.bArticleInfoService.setNullArticleBrandId(bVideoInfo.getId());
                this.bVideoInfoService.save(bVideoInfo);
                this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByTypeForHotValue" + articleTypeInfoEntity.getId());
                // 向头条标题添加关联 start yl 20200624
                if (StringUtils.isNoneBlank(bVideoInfo.getHeadlineTitleIds())){
                    //SysUserEntity curUser = getUser();
                    this.bArticleInfoService.headlineRelation(bVideoInfo.getId(), Arrays.stream(bVideoInfo.getHeadlineTitleIds()
                            .split(","))
                            .map(s -> Integer.valueOf(s.trim()))
                            .collect(Collectors.toList()),curUser.getUserId().intValue());
                }
                // 向头条标题添加关联 end yl 20200624

                // 文章公众号关联
                BArticleGzh bArticleGzhSave = new BArticleGzh();
                // 文章id
                bArticleGzhSave.setArticleId(bVideoInfo.getId());
                // 公众号标识
                bArticleGzhSave.setGzhCode(bVideoInfo.getGzhCode());
                // 先删除
                if(this.bArticleGzhService.queryByArticleId(bVideoInfo.getId()) != null) {
                    this.bArticleGzhService.deleteByArticleId(bVideoInfo.getId());
                }
                // 再保存
                if((bArticleGzhSave.getGzhCode() != null) && (!bArticleGzhSave.getGzhCode().equals("-1")) && (!"".equals(bArticleGzhSave.getGzhCode().trim()))) {
                    this.bArticleGzhService.insertOne(bArticleGzhSave);
                }

                return R.ok();
            }
            return R.error("所选的类型不存在");
        }

        if (!bVideoInfo.getBrandName().equals("")){
            String[] brandNames = bVideoInfo.getBrandName().split(",");
            if (brandNames != null) {
                for(int i = 0; i < brandNames.length; i++) {
                    BBrandInfoEntity brandInfoEntity = new BBrandInfoEntity();
                    brandInfoEntity.setId((this.bBrandInfoService.queryByName(brandNames[i])).getId());
                    if(brandInfoEntity == null){
                        return R.error("所选的品牌不存在");
                    }
                    bVideoInfo.setArticleBrandId(brandInfoEntity.getId());
                    // 删除品牌 top50 缓存 start
                    String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + brandInfoEntity.getId();
                    redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
                    // 删除品牌 top50 缓存 end
                    String brandId = bVideoInfo.getArticleBrandId().toString();
                    int total = this.bVideoInfoService.titleTotal(bVideoInfo.getArticleTitle(), brandId).intValue();
                    if (total == 0){
                        this.bArticleInfoService.setNullArticleTypeId(bVideoInfo.getId());
                        this.bVideoInfoService.save(bVideoInfo);
                        this.redisCacheUtil.removeSingleCache("recommendHotVideoInfoByBrandForHotValue" + brandInfoEntity.getId());
                        // 向头条标题添加关联 start yl 20200624
                        if (StringUtils.isNoneBlank(bVideoInfo.getHeadlineTitleIds())){
                            //SysUserEntity curUser = getUser();
                            this.bArticleInfoService.headlineRelation(bVideoInfo.getId(), Arrays.stream(bVideoInfo.getHeadlineTitleIds()
                                    .split(","))
                                    .map(s -> Integer.valueOf(s.trim()))
                                    .collect(Collectors.toList()),curUser.getUserId().intValue());
                        }
                    }
                }
                return R.ok();
            }
            return R.error("所选的品牌不存在");
        }
        logger.info("新增视频:" + bVideoInfo.getArticleTitle());
        return R.error("新增视频失败");
    }

    private String updateImgs(String videoContent)
            throws IOException
    {
        Document document = null;
        document = Jsoup.parse(videoContent);

        Elements imgElements = document.select("img");
        for (Element img : imgElements)
        {
            String src = "";
            src = AliyunOssClientUtil.uploadFileByFileUrl2(img.attr("src"));
            img.attr("src", src);
        }
        return document.body().html();
    }

    @RequestMapping({"/update"})
    @RequiresPermissions({"sys:barticleinfo:update"})
    public R update(@RequestBody BArticleInfoEntity bArticleInfo)
            throws Exception
    {
        ValidatorUtils.validateEntity(bArticleInfo, new Class[0]);
        String cacheKey = bArticleInfo.getId() + "ArticleDetailInfoKey";
        System.out.println(cacheKey);
        if ((bArticleInfo.getArticleStatus() != null) && (bArticleInfo.getArticleStatus().intValue() == 0))
        {
            bArticleInfo.setArticleStatus(Integer.valueOf(0));
            bArticleInfo.setRedisStoreStatus(Integer.valueOf(2));

            this.redisCacheUtil.removeSingleCacheMaster(cacheKey);
        }
        BArticleInfoEntity dataArticleInfo = this.bArticleInfoService.getById(bArticleInfo.getId());
        if (dataArticleInfo.getArticleBrandId() != null) {
            // 删除品牌 top50 缓存 start
            String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + dataArticleInfo.getArticleBrandId();
            redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
            // 删除品牌 top50 缓存 end
        }

        if (dataArticleInfo.getArticleTypeId() != null) {
            // 删除分类 top50 缓存 start
            String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + dataArticleInfo.getArticleTypeId();
            redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
            // 删除分类 top50 缓存 end
        }
        HttpGetPostUtils.delCache(this.serviceUrls, "ArticleInfoMapper");
        bArticleInfo.setModifyTime(new Date());
        this.bArticleInfoService.updateById(bArticleInfo);
        return R.ok();
    }

    @RequestMapping({"/updateInfo"})
    @RequiresPermissions({"sys:barticleinfo:update"})
    public R updateInfo(@RequestBody BArticleInfoEntity bVideoInfo)
            throws Exception
    {

        for(String k: SysConstant.KeyWorks){
            if(bVideoInfo.getArticleTitle()!=null && bVideoInfo.getArticleTitle().contains(k)){
                return R.error("标题中不能包含“"+k+"”，请检查后修正.");
            }
            if(bVideoInfo.getArticleDesc()!=null && bVideoInfo.getArticleDesc().contains(k)){
                return R.error("配文中不能包含“"+k+"”，请检查后修正.");
            }
        }

        if ((bVideoInfo.getBrandName().equals("")) && (bVideoInfo.getArticleTypeName().equals(""))) {
            return R.error("请选择品牌或分类");
        }
        ValidatorUtils.validateEntity(bVideoInfo, new Class[0]);
        String cacheKey = bVideoInfo.getId() + "ArticleDetailInfoKey";
        System.out.println(cacheKey);
        if ((bVideoInfo.getArticleStatus() != null) && (bVideoInfo.getArticleStatus().intValue() == 0))
        {
            bVideoInfo.setArticleStatus(Integer.valueOf(0));
            bVideoInfo.setRedisStoreStatus(Integer.valueOf(2));
        }
        Boolean redisDel = Boolean.valueOf(this.redisCacheUtil.removeSingleCacheMaster(cacheKey));
        System.out.println("***** BArticleInfoController updateInfo redisDel:" + redisDel + " _ cacheKey:" + cacheKey);

        HttpGetPostUtils.delCache(this.serviceUrls, "ArticleInfoMapper");
        bVideoInfo.setModifyTime(new Date());

        bVideoInfo.setArticleBrandId(null);
        bVideoInfo.setArticleTypeId(null);
        // 先删除关联的头条标题
        this.bArticleInfoService.delHeadlineRelation(bVideoInfo.getId());
        if (!bVideoInfo.getBrandName().equals(""))
        {
            BBrandInfoEntity brandInfoEntity = this.bBrandInfoService.queryByName(bVideoInfo.getBrandName());
            if (brandInfoEntity != null)
            {
                bVideoInfo.setArticleBrandId(brandInfoEntity.getId());
                // 删除品牌 top50 缓存 start
                String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + brandInfoEntity.getId();
                redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
                // 删除品牌 top50 缓存 end
                this.bArticleInfoService.setNullArticleTypeId(bVideoInfo.getId());
                this.bArticleInfoService.updateById(bVideoInfo);
                updateSourceHeight(bVideoInfo.getId(), bVideoInfo.getVideoHeight());
                // 向头条标题添加关联 start yl 20200624
                if (StringUtils.isNoneBlank(bVideoInfo.getHeadlineTitleIds())){
                    SysUserEntity curUser = getUser();
                    this.bArticleInfoService.headlineRelation(bVideoInfo.getId(), Arrays.stream(bVideoInfo.getHeadlineTitleIds()
                            .split(","))
                            .map(s -> Integer.valueOf(s.trim()))
                            .collect(Collectors.toList()),curUser.getUserId().intValue());
                }
                // 向头条标题添加关联 end yl 20200624
                return R.ok();
            }
            return R.error("所选的品牌不存在");
        }
        if (!bVideoInfo.getArticleTypeName().equals(""))
        {
            BArticleTypeInfoEntity articleTypeInfoEntity = this.bArticleTypeInfoService.queryByName(bVideoInfo.getArticleTypeName());
            if (articleTypeInfoEntity != null)
            {
                bVideoInfo.setArticleTypeId(articleTypeInfoEntity.getId());
                // 删除分类 top50 缓存 start
                String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + articleTypeInfoEntity.getId();
                redisCacheUtil.removeSingleCacheMaster(articleTypeIdKey);
                // 删除分类 top50 缓存 end
                this.bArticleInfoService.setNullArticleBrandId(bVideoInfo.getId());
                this.bArticleInfoService.updateById(bVideoInfo);
                updateSourceHeight(bVideoInfo.getId(), bVideoInfo.getVideoHeight());
                // 向头条标题添加关联 start yl 20200624
                if (StringUtils.isNoneBlank(bVideoInfo.getHeadlineTitleIds())){
                    SysUserEntity curUser = getUser();
                    this.bArticleInfoService.headlineRelation(bVideoInfo.getId(), Arrays.stream(bVideoInfo.getHeadlineTitleIds()
                            .split(","))
                            .map(s -> Integer.valueOf(s.trim()))
                            .collect(Collectors.toList()),curUser.getUserId().intValue());
                }
                // 向头条标题添加关联 end yl 20200624
                return R.ok();
            }
            return R.error("所选的类型不存在");
        }
        logger.info("更新视频:" + bVideoInfo.getArticleTitle());
        return R.error("新增视频失败");
    }

    @Async
    void updateSourceHeight(Integer id, Integer height)
    {
        if ((null != id) && (null != height)) {
            this.bArticleInfoService.updateSourceHeight(id, height);
        }
    }
    @RequestMapping({"/delete"})
    @RequiresPermissions({"sys:barticleinfo:delete"})
    public R delete(@RequestBody Integer[] ids)
    {
        this.bVideoInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping({"/commit1"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    @ResponseBody
    public R request(@RequestBody String wxVideoUrl)
            throws Exception
    {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://192.168.5.147:8888/spiderChaoVcardInfo/");
        String json = "{\"wxVideoUrl\":" + wxVideoUrl + "}";
        StringEntity postingString = new StringEntity(json);
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());

        JSONObject jsonObject = JSONObject.fromObject(content);
        String videoContent = jsonObject.get("content").toString();
        return R.ok().put("content", jsonObject).put("family", videoContent);
    }

    @RequestMapping({"/commit"})
    @RequiresPermissions({"sys:barticleinfo:list"})
    @ResponseBody
    public R requests(@RequestBody String wxVideoUrl)
            throws Exception
    {
        String content = getContentByUrl(wxVideoUrl);

        JSONObject jsonObject = JSONObject.fromObject(content);

        String contents = jsonObject.get("data").toString();
        String code = jsonObject.get("code").toString();
        if (code.equals("2")) {
            return R.error("文章内容过短。");
        }
        if (code.equals("3")) {
            return R.error("文章内容过短。");
        }
        if (code.equals("4")) {
            return R.error("文章可能涉嫌违规");
        }
        jsonObject = JSONObject.fromObject(contents);
        String videoContent = jsonObject.get("video_content").toString();

        videoContent = getAfterVideoContent(videoContent);
        return R.ok().put("content", jsonObject).put("family", videoContent);
    }

    private String getContentByUrl(String wxVideoUrl)
            throws Exception
    {
        HttpClient httpClient = HttpClientBuilder.create().build();
        String profile = SpringContextUtil.getActiveProfile();
        String url = "";
        if (profile.equals("dev")) {
            url = "http://120.78.222.19/snippetsFormatText/";
        } else {
            url = "http://120.78.222.19/snippetsFormatText/";
        }
        HttpPost post = new HttpPost(url);
        String json = "{\"wxVideoUrl\":" + wxVideoUrl + "}";
        StringEntity postingString = new StringEntity(json);
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        return content;
    }

    private String getAfterVideoContent(String videoContent)
    {
        Document htmlDoc = Jsoup.parse(videoContent);

        Element headDiv = htmlDoc.select("div#js_content").first();
        headDiv.attr("style", "max-width: 100%;");

        Elements imgs = htmlDoc.select("img");
        for (Element e : imgs) {
            e.attr("src", e.attr("data-src"));
        }
        logger.info("*******videoContent:" + htmlDoc.html());
        return htmlDoc.html();
    }

    @RequestMapping({"/createrInfo"})
//    @RequiresPermissions({"sys:barticleinfo:createrInfo"})
    public R createrInfo(@RequestBody String douDouShareLink) throws IOException {
        //先判断是否为空
        String userSendContent = douDouShareLink;

        if (StringUtils.isBlank(userSendContent)) {
            return R.error("请输入分享内容！");
        }

        BArticleInfoEntity articleInfoDto = null;

        if(StringUtils.isNotBlank(userSendContent) && userSendContent.contains("v.douyin.com")) {
            //抖音链接变文章
            articleInfoDto = VideoParse.parseUrl(douDouShareLink, "tcould");
        }else{
            return R.error("不含抖抖链接是不行的哦！");
        }

        return R.ok().put("articleInfoDto",articleInfoDto);
    }

    @RequestMapping({"/createrInfowx"})
//    @RequiresPermissions({"sys:barticleinfo:createrInfo"})
    public R createrInfowx(@RequestBody String WeiXinShareLink) throws IOException {
        //先判断是否为空
        String userSendContent = WeiXinShareLink;

        if (StringUtils.isBlank(userSendContent)) {
            return R.error("请输入分享内容！");
        }
        String finalVideoAddress="http://mpvideo.qpic.cn/0bf2m4ecwaaicmagz4ejm5pvqz6dfntqqkya.f10002.mp4?dis_k=c08a817cb79b6acd36a287a2cae3195a&dis_t=1614403105&vid=wxv_1555511087976988674&format_id=10002";
        BArticleInfoEntity bArticleInfo = VideoParse.downVideo(finalVideoAddress, "title", "抖音视频", "userId");

        if(StringUtils.isNotBlank(userSendContent) && userSendContent.contains("v.douyin.com")) {

        }else{
            return R.error("不含抖抖链接是不行的哦！");
        }

        return R.ok().put("bArticleInfo",bArticleInfo);
    }

    @RequestMapping({"/getWeiXinPage"})
//    @RequiresPermissions({"sys:barticleinfo:createrInfo"})
    public R getWeiXinPage(@RequestBody String WeiXinShareLink) throws IOException {
        //先判断是否为空
        String userSendContent = WeiXinShareLink;

        if (StringUtils.isBlank(userSendContent)) {
            return R.error("请输入分享内容！");
        }
        if(StringUtils.isNotBlank(userSendContent) && userSendContent.contains("mp.weixin.qq.com")) {
            //BArticleInfoEntity bArticleInfo = WebSpiderThreadUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            //BArticleInfoEntity bArticleInfo2 = WebSpiderUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            ArticleInfoTemp item = WebSpiderThreadUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();
            bArticleInfo.setArticleTitle(item.getArticleTitle());
            bArticleInfo.setArticleDesc(item.getArticleDesc());
            bArticleInfo.setArticleImgUrl(item.getArticleImgUrl());
            bArticleInfo.setArticleContent(item.getArticleContent());

            bArticleInfo.setCreateTime(new Date());
            bArticleInfo.setModifyTime(new Date());
            bArticleInfo.setCreateUser(getUser().getUsername());
            bArticleInfo.setArticleSource(Integer.valueOf(1));// 文章来源 1-平台添加 2-用户通过公众号添加 3-用户编辑的文章生成自己的文章
            bArticleInfo.setArticleStatus(Integer.valueOf(2));// 文章状态 0-删除 1-正常 2-隐藏
            bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
            bArticleInfo.setSType("后台录入");

            bArticleInfo.setArticleLevel(Integer.valueOf(1)); // 经典文章 0-是 1-否
            bArticleInfo.setHtTemplateId(Integer.valueOf(1)); // 经典标题 0-是 1-否
            bArticleInfo.setArticleVersionNum(Integer.valueOf(2)); // 显示类型 0-大图 2- 常规
            bArticleInfo.setHotType(Integer.valueOf(0)); // 热度类型 0-随机 1-自定义

            this.bArticleInfoService.save(bArticleInfo);
            Integer resultId = bArticleInfo.getId();
            return R.ok().put("bArticleInfo",bArticleInfo).put("resultId",resultId);
        }else{
            return R.error("不是微信公众号文章链接！");
        }
    }

    @RequestMapping({"/getWeiXinPage2"})
//    @RequiresPermissions({"sys:barticleinfo:createrInfo"})
    public R getWeiXinPage2(@RequestBody String WeiXinShareLink) throws IOException {
        //先判断是否为空
        String userSendContent = WeiXinShareLink;

        if (StringUtils.isBlank(userSendContent)) {
            return R.error("请输入分享内容！");
        }
        if(StringUtils.isNotBlank(userSendContent) && userSendContent.contains("mp.weixin.qq.com")) {
            //BArticleInfoEntity bArticleInfo = WebSpiderThreadUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            //BArticleInfoEntity bArticleInfo2 = WebSpiderUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));

            ArticleInfoTemp item = WebSpiderThreadUtil.getWeiXinPage2(userSendContent.trim().replaceAll("\"",""));
            //ArticleInfoTemp item =null;

            BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();
            bArticleInfo.setArticleTitle(item.getArticleTitle());
            bArticleInfo.setArticleTypeId(Integer.valueOf(57));// 文章分类
            bArticleInfo.setArticleDesc(item.getArticleDesc());
            // bArticleInfo.setArticleImgUrl(item.getArticleImgUrl());
            bArticleInfo.setArticleContent(item.getArticleContent());

            bArticleInfo.setCreateTime(new Date());
            bArticleInfo.setModifyTime(new Date());
            bArticleInfo.setCreateUser(getUser().getUsername());
            bArticleInfo.setArticleSource(Integer.valueOf(1));// 文章来源 1-平台添加 2-用户通过公众号添加 3-用户编辑的文章生成自己的文章
            bArticleInfo.setArticleStatus(Integer.valueOf(2));// 文章状态 0-删除 1-正常 2-隐藏
            bArticleInfo.setSpiderProcessStatus(Integer.valueOf(1));
            bArticleInfo.setSType("后台录入");

            bArticleInfo.setArticleLevel(Integer.valueOf(1)); // 经典文章 0-是 1-否
            bArticleInfo.setHtTemplateId(Integer.valueOf(1)); // 经典标题 0-是 1-否
            bArticleInfo.setArticleVersionNum(Integer.valueOf(2)); // 显示类型 0-大图 2- 常规
            bArticleInfo.setHotType(Integer.valueOf(0)); // 热度类型 0-随机 1-自定义

            this.bArticleInfoService.save(bArticleInfo);
            Integer resultId = bArticleInfo.getId();
            return R.ok().put("bArticleInfo",bArticleInfo).put("resultId",resultId);
        }else{
            return R.error("不是微信公众号文章链接！");
        }
    }

    @RequestMapping({"/getWeiXinPageNo"})
//    @RequiresPermissions({"sys:barticleinfo:createrInfo"})
    public R getWeiXinPageNo(@RequestBody String WeiXinShareLink) throws IOException {
        //先判断是否为空
        String userSendContent = WeiXinShareLink;

        if (StringUtils.isBlank(userSendContent)) {
            return R.error("请输入分享内容！");
        }
        if(StringUtils.isNotBlank(userSendContent) && userSendContent.contains("mp.weixin.qq.com")) {
            ArticleInfoTemp item = WebSpiderThreadUtil.getWeiXinPage(userSendContent.trim().replaceAll("\"",""));
            BArticleInfoEntity bArticleInfo = new BArticleInfoEntity();
            bArticleInfo.setArticleTitle(item.getArticleTitle());
            bArticleInfo.setArticleDesc(item.getArticleDesc());
            bArticleInfo.setArticleImgUrl(item.getArticleImgUrl());
            bArticleInfo.setArticleContent(item.getArticleContent());

            return R.ok().put("bArticleInfo",bArticleInfo);
        }else{
            return R.error("不是微信公众号文章链接！");
        }
    }
}
